<?php
/**
 * 创建控制器文件，集所有处理逻辑于大成
 */

namespace plugins\qbt_custom_model\service;

use think\Db;

class CreateControllerService
{

    private $content = '';

    public function __construct($info = [])
    {
        $this->content = $this->get_path();
        $this->get_model_name($info);
        $field_info = Db::name("model_field")->where(["model_id" => $info['model_id'], "field_add_show" => 1])->select()->toArray();
        $field_info_edit = Db::name("model_field")->where(["model_id" => $info['model_id'], "field_edit_show" => 1])->select()->toArray();
        $this->content = $this->get_edit($field_info, $info);
        $this->content = $this->get_add($field_info_edit, $info);
        $this->content = $this->get_addpost_editpost($field_info, $info);
        $this->content = $this->get_id();
        $this->content = $this->get_list($field_info, $info);
        $this->content = $this->change_status();
        $file_name = $this->get_controller_name($info['model_controller']);
        file_put_contents($file_name, $this->content);
    }

    /**
     * 获取模版路径并载入，返回内容
     */
    private function get_path()
    {
        $path = str_replace("\\", DS, dirname(__DIR__)) . DS . 'data' . DS . 'tpl' . DS . 'controllers.tpl';
        $content = file_get_contents($path);
        return $content;
    }

    /**
     * 获取控制器名称,返回控制器文件名，带路径
     */
    private function get_controller_name($model_controller = "")
    {
        $fileName = APP_PATH . "admin/controller/" . $model_controller . "Controller.php";
        return $fileName;
    }

    /**
     * 获取对应模型名称、验证名称、控制器类名、描述并替换对应内容
     */
    private function get_model_name($model)
    {
        $tabarr = explode("_", $model['model_tabname']);
        $name = '';
        if (count($tabarr) > 1) {
            foreach ($tabarr as $v) {
                $name .= ucfirst($v);
            }
        } else {
            $name = ucfirst($tabarr[0]);
        }
        $model_name = $name . "Model";
        $controller_name = $model['model_controller'] . "Controller";
        $this->content = str_replace(array("#MODELNAME#", "#CONTROLLERNAME#", "#DESC#", "#VALIDATENAME#"), array($model_name, $controller_name, $model['model_name'], $name), $this->content);
        return $this->content;
    }

    /**
     * 获取添加、编辑表单逻辑，并替换,有外键的时候会取出其他表数据
     */
    private function get_add($field_info, $data)
    {
        $str = '';
        foreach ($field_info as $k => $v) {
            if ($v['field_type'] == "outreach") {
                $tb = explode('.', $v['field_outreach']);
                $str .= '$' . $v['field_name'] . ' = Db::table("' . $tb[0] . '")->select()->toArray();';
                $str .= '
        $this->assign("' . $v['field_name'] . '",$' . $v['field_name'] . ');
        ';
            }
        }
        #nsh 20190107 修改
        if ($data['distinguish'] == 1) {
            $str .= '$parentId            = $this->request->param(\'parent\', 0, \'intval\');
        $portalCategoryModel = new '.$data['model_name'].'Model();
        $categoriesTree      = $portalCategoryModel->adminCategoryTree($parentId);
        $this->assign(\'parentId\', $parentId);
        $this->assign(\'categories_tree\', $categoriesTree);';
        }
        
        $this->content = str_replace(array("#ADD_TODO#", "#EDIT_TODO#"), $str, $this->content);
        return $this->content;
    }

    /**
     * 获取添加、编辑表单逻辑，并替换,有外键的时候会取出其他表数据
     */
    private function get_edit($field_info, $data)
    {
        $str = '';
        foreach ($field_info as $k => $v) {
            if ($v['field_type'] == "outreach") {
                $tb = explode('.', $v['field_outreach']);
                $str .= '$' . $v['field_name'] . ' = Db::table("' . $tb[0] . '")->select()->toArray();';
                $str .= '
        $this->assign("' . $v['field_name'] . '",$' . $v['field_name'] . ');
        ';
            } elseif ($v['field_type'] == "images" || $v['field_type'] == "files") {
                $str .= '
                    $info["' . $v['field_name'] . '"] = json_decode($info["' . $v['field_name'] . '"],true);
                ';
            }
        }
        #nsh 20190107 修改
        if ($data['distinguish'] == 1) {
            $str .= '$category = ArticleCategoryModel::get($id)->toArray();
        $portalCategoryModel = new ArticleCategoryModel();
        $categoriesTree      = $portalCategoryModel->adminCategoryTree($category[\'parent_id\'], $id);
        $this->assign(\'categories_tree\', $categoriesTree);';
        }


        $this->content = str_replace(array("#EDIT_TODO#"), $str, $this->content);
        return $this->content;
    }

    /**
     * 获取添加、编辑表单提交数据处理
     */
    private function get_addpost_editpost($field_info, $data)
    {
        $str = '';
        $str2 = '';
        foreach ($field_info as $k => $v) {
            if (in_array($v['field_type'], array('checkbox', 'image', 'images', 'file', 'files', 'datetime'))) {
                $str .= CtrlService::task($v['field_type'], $field_info[$k]);
                $str2 .= CtrlService::task($v['field_type'], $field_info[$k]);
            }
        }
        $str  .= '$data["create_time"] = time();';
        $str  .= '$data["update_time"] = time();';
        $str2 .= '$data["update_time"] = time();';
        $this->content = str_replace(array("#ADDPOST#", "#EDITPOST#"), array($str, $str2), $this->content);
        return $this->content;
    }

    /**
     * 获取id
     */
    private function get_id()
    {
        $this->content = str_replace(array("#ID#"), array('id'), $this->content);
        return $this->content;
    }

    /**
     * 替换list
     */
    private function get_list($field_info, $data)
    {
        $pre = config("database.prefix");
        #nsh 20190107 修改
        if ($data['distinguish'] == 1) {
            $html = '$where = [];
        $keyword             = $this->request->param(\'keyword\');
        if (empty($keyword)) {

            $categoryTree = $model->adminCategoryTableTree();
            $this->assign(\'category_tree\', $categoryTree);
        } else {
            $categories = $model->where(\'title\', \'like\', "%{$keyword}%")
                ->select();
            $this->assign(\'categories\', $categories);
        }
        $this->assign(\'keyword\', $keyword);';
        } elseif ($data['distinguish'] == 2) {
            $html = '
            $where = [];
            if(isset($param["keyword"])){
                $where["m.title"] = ["like","%{$param["keyword"]}%"];
                $this->assign(\'keyword\', $param["keyword"]);
            }
        ';
            $outreach = [];
            foreach ($field_info as $k => $v) {
                if ($v['field_type'] == 'outreach') {
                    $outreach[$v['field_id']] = $v;
                }
            }
            if (count($outreach) > 0) {
                $html .= '$lists = $model->alias("m")->field("m.*';
                foreach ($outreach as $p => $q) {
                    $tarr = explode('.', $q['field_outreach']);
                    foreach ($tarr as $k => $vl) {
                        if ($k > 1) {
                            $arr_v = explode('=', $vl);
                            if (is_array($arr_v)) {
                                $html .= ',a' . $p . '.' . $arr_v[1] . ' as ' . $tarr[0] . '_' . $arr_v[1];
                            }
                        }
                    }
                }
                $html .= '")';
                foreach ($outreach as $p => $q) {
                    $tarr = explode('.', $q['field_outreach']);
                    $tbname = substr($tarr[0], strlen($pre));
                    $html .= '->join("' . $tbname . ' a' . $p . '","a' . $p . '.' . $tarr[1] . ' = m.' . $q['field_name'] . '")';
                }
                $html .= '->where($where)->order("m.listorder asc,m.id asc")->paginate(10);';
                $html .= '
                $page = $lists->render();
                // 模板变量赋值
                $this->assign(\'lists\', $lists);
                $this->assign(\'page\', $page);
            ';
            } else {
                $html .= '
            $lists = $model->alias("m")->where($where)->order("listorder asc,id asc")->paginate(10);
            $page = $lists->render();
            // 模板变量赋值
            $this->assign(\'lists\', $lists);
            $this->assign(\'page\', $page);
            ';
            }
        }
        $this->content = str_replace("#GET_LIST#", $html, $this->content);
        return $this->content;
    }

    /**
     * 状态修改
     */
    public function change_status()
    {
        $this->content = str_replace(array("#listorder#", "#status#"), array("listorder", "status"), $this->content);
        return $this->content;
    }

}